let _Vue = null
export default class VueRouter {
  static install(Vue) {
    // 1 判断当前插件是否已经安装
    if (VueRouter.install.installed) return
    VueRouter.install.installed = true
    // 2 把Vue构造函数记录到全局变量
    _Vue = Vue
    // 3 创建Vue实例的时候将传入的router对象注入到Vue实例上
    _Vue.mixin({
      beforeCreate() {
        // 判断当前是Vue实例还是Vue的组件，只有在实例中才执行。
        if (this.$options.router) {
          _Vue.prototype.$router = this.$options.router
        }
      },
    })
  }
  constructor(options) {
    this.options = options
    this.routeMap = {}
    this.data = _Vue.observable({
      current: '/',
    })
    this.init()
  }
  init() {
    this.createRouteMap()
    this.initComponent(_Vue)
    this.initEvent()
  }
  // 将传入的router对象，以键值对形式，键为当前路由的path, 值为当前路由的component，存入到routeMap中
  createRouteMap() {
    this.options.routes.forEach((route) => {
      this.routeMap[route.path] = route.component
    })
  }
  // 创建全局组件
  initComponent(Vue) {
    // 全局组件router-link
    Vue.component('router-link', {
      props: {
        to: {
          type: String,
          default: '/',
        },
      },
      methods: {
        clickHander(e) {
          location.hash = this.to
          this.$router.data.current = this.to
          e.preventDefault()
        },
      },
      render(h) {
        return h(
          'a',
          {
            attrs: {
              herf: this.to,
            },
            on: {
              click: this.clickHander,
            },
          },
          [this.$slots.default]
        )
      },
    })
    // 全局组件router-view
    const _this = this
    Vue.component('router-view', {
      render(h) {
        const cm = _this.routeMap[_this.data.current]
        return h(cm)
      },
    })
  }
  initEvent() {
    //首次进来
    this.jump()
    window.onhashchange = () => {
      //hash值变化
      this.jump()
    }
  }
  jump() {
    //获取路由#后面的值
    const hash = window.location.hash.slice(1).split('?')[0]
    //如果hash有值
    if (hash) {
      let currentRouter = this.options.routes.filter(
        (item) => item.path === hash
      )[0]
      if (!currentRouter) {
        // 如果hash地址未定义过则跳转至/notfound页面
        currentRouter = this.options.routes.filter(
          (item) => item.path === '/notfound'
        )[0]
      }
      location.hash = currentRouter.path
      this.data.current = currentRouter.path
    } else {
      // hash没有值则说明是首页面
      location.hash = this.data.current
    }
  }
}
